<template>


  <div>
      <van-nav-bar left-text="返回" @click-left='prev' left-arrow/>

      <div id="chatHistory" style="overflow:auto;" :style="{height: scrollerHeight}">
        <van-row v-for="(item, index) in receiveMsgList" :key="index" type="flex" justify="center" style="margin-top: 6%; ">

          <van-col class="van-col-width"  v-if="item.flag">
            <van-image style="float: left" width="50" height="50" src="https://img.yzcdn.cn/vant/cat.jpeg"/>
            <van-cell  class="content msgContent left" center :value="item.message" />
          </van-col>

          <van-col class="van-col-width" v-else>
            <van-image style="float: right" width="50" height="50" src="https://img.yzcdn.cn/vant/cat.jpeg"/>
            <van-cell  class="content msgContent right" center :value="item.message"/>
          </van-col>

        </van-row>
      </div>


    <van-field v-model="message" style="position: fixed; bottom: 0;  background-color: #f7f8fa " center clearable id="talksub">
      <template #button>
        <van-button size="small" type="primary" @click="sendMsg">发送</van-button>
      </template>
    </van-field>

  </div>
</template>

<script>
  export default {
    name: "Chat",
    data() {
      return {
        message: '',
        webSocket: null,
        receiveMsgList: []
      };
    },
    created() {
      // this.initWebSocket();
    },
    destroyed() {
      this.webSocket.close();
    },
    computed: {
        scrollerHeight: function() {
            return  (window.innerHeight - 46 - 50) + 'px';
        }
    },
      methods: {
      initWebSocket() {
        const chatUri = "ws://192.168.1.104:8088/ws";
        this.websock = new WebSocket(chatUri);
        this.websock.onmessage = this.webSocketOnMessage;
        this.websock.onopen = this.webSocketOnOpen;
        this.websock.onerror = this.webSocketOnError;
        this.websock.onclose = this.webSocketClose;
      },
      webSocketOnOpen() {
        let sendUserId  = JSON.parse(sessionStorage.getItem("userInfo")).id;
        // 连接建立之后执行send方法发送数据{sendUserId,acceptUserId,message}
        let initMessage = {"sendUserId": sendUserId, "acceptUserId": "init", "messageType":"init"};
        this.webSocketSend(JSON.stringify(initMessage));
      },
      webSocketOnError() {//连接建立失败重连
        // this.initWebSocket();
      },
      webSocketOnMessage(e) {//数据接收
        this.receiveMsgList.push(JSON.parse(e.data))
        console.log('数据内容：', e.data)
      },
      webSocketSend(Data) {//数据发送
        this.websock.send(Data);
        console.log("send" + Data)
      },
      webSocketClose(e) {  //关闭
        console.log('断开连接', e);
      },
      sendMsg() {
        // let acceptUserId = this.$route.params.acceptUserId;
        // // alert(acceptUserId)
        // let sendUserId  = JSON.parse(sessionStorage.getItem("userInfo")).id;
        // let initMessage = {"sendUserId": sendUserId, "acceptUserId": acceptUserId, "message": this.message,"flag":false, "init":false};
        // this.webSocketSend(JSON.stringify(initMessage));
          var chatHistory = document.getElementById('chatHistory');

          var newChatMsg = '' +
              '<div data-v-27a533a5="" class="van-col-width van-col" style="margin-top: 5px">' +
                '<div data-v-27a533a5="" class="van-image" style="width: 50px; height: 50px; float: left;">' +
                  '<img src="https://img.yzcdn.cn/vant/cat.jpeg" class="van-image__img">' +
                '</div>' +
                '<div data-v-27a533a5="" class="content msgContent left van-cell van-cell--center">' +
                  '<div class="van-cell__value van-cell__value--alone">' +
                    '<span >'+this.message+'</span>' +
                  '</div>' +
                '</div>' +
              '</div>'
          chatHistory.innerHTML = chatHistory.innerHTML + newChatMsg
          var chatHistoryHeight = document.getElementById('chatHistory').scrollHeight;
          chatHistory.scrollTop = chatHistoryHeight
          // this.message="";

      },
      prev() {
        this.$router.push({path:'/home'})
      }
    },

  }

</script>

<style scoped>

  .van-col-width {
    width: 90%;
  }

  .content {
    list-style: none;
    width: 410px;
    height: 280px;
    margin: 5px auto;
    border: 1px dotted #D1D3D6;
    overflow-y: scroll;
  }

  .msgContent {
    width: auto;
    max-width: 70%;
    height: auto;
    word-break: break-all;
    margin: 5px;
    padding: 3px;
    border-radius: 5px;
  }

   .left {
    float: left;
    text-align: left;
    background-color: lightgrey;
  }

   .right {
    float: right;
    text-align: right;
    background-color: #07c160;
  }
</style>